import paramiko
import time
import re

switch_command = {
    'cpu': 'show cpu | include CPU',
    'mem': 'show memory',
    'clock': 'show clock',
    'fan': 'show fan'
}
switch_pattern = {
    'cpu': r'\d{1,2}\.\d+%|\d%',
    'mem': r'\d{1,2}%|\d{1,2}\.\d%',
    'clock': r'\d+:\d+:\d+'
}
command_order = ['cpu', 'mem', 'clock']


class Switch:
    def __init__(self, host, user, pwd):
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(host, port=22, username=user, password=pwd, timeout=3)
        self.switch = self.client.invoke_shell()
        self.switch.send('enable\n')
        self.switch.send('iflyun\n')
        # time.sleep(1)

    def command(self, cmd):
        self.switch.send(cmd + '\n')
        time.sleep(1)
        byte_buffer = b''
        while True:
            _buffer = self.switch.recv(2000)
            byte_buffer += _buffer
            str_buffer = _buffer.decode('utf-8')

            if '--More--' in str_buffer:  # 执行空格将继续接收数据。
                self.switch.send(' ')
                # time.sleep(1)
            elif str_buffer.endswith('>') or str_buffer.endswith('#'):  # 缓冲区数据结尾是>或#说明命令已经结束。
                break

        return byte_buffer

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client.close()


def commands(all_ip: list, all_cmd: list):
    all_data = []
    all_data.append(['IP', '5sec', '1min', '5min', 'mem', 'clock'])
    for ip in all_ip:
        ip = ip.strip()
        try:
            switch = Switch(ip, 'zhang', '*')
        except Exception as e:
            single_data = [ip]
            single_data += ['no data']
            continue
        single_data = [ip]

        for cmd in all_cmd:
            cmd_data = switch.command(switch_command[cmd])
            filter_data = re.findall(switch_pattern[cmd], cmd_data.decode('utf-8'))
            if cmd == 'cpu' or cmd == 'mem':
                convert_data = []
                for _data in filter_data:
                    convert_data.append(float(_data.split('%')[0]))

                if len(filter_data) > 3:
                    grouping_data = [[convert_data[i], convert_data[i + 1], convert_data[i + 2]] for i in range(1, len(convert_data)) if i % 3 == 0]
                    _max = 0
                    for index in range(1, len(grouping_data)):
                        if sum(grouping_data[_max]) < sum(grouping_data[index]):
                            _max = index
                    single_data += grouping_data[_max]
                    continue
                else:
                    single_data += convert_data
                    continue
            single_data += filter_data
            print(single_data)
        all_data.append(single_data)
    return all_data


def main():
    # excel = SingleExcel(write_path=r'g:\test.xlsx')
    all_ip = []
    with open(r'g:\config.txt') as file:
        for ip in file:
            ip = ip.strip()
            all_ip.append(ip)
    data = commands(all_ip, ['fan'])
    # from mytool.office.chart import Barchart
    # b = Barchart()
    # b.add_chart(data, 'H1')
    # b.save_chart(r'g:\\t.xlsx')
    # excel.add_sheet('test')
    # excel.write_all_sheet(data, 'test')


if __name__ == '__main__':
    # main()
    s = Switch('172.23.1.140', 'zhang', 'zhangchen@123')
    r = s.command('show temp')
    print(r.decode())
